<script setup>

import { onMounted, ref, watch } from 'vue'
import { queryClassApi, addClazzApi, updateClazzApi, queryByIdApi,deleteClazzApi } from '@/api/clazz';
import { ElMessageBox, ElMessage } from 'element-plus';
import { queryAllEmpApi } from '@/api/emp';





//定义搜索框数据模型
const searchClazz = ref({
  name: '',
  date: [],
  begin: '',
  end: ''
})


//钩子函数
onMounted(() => {
  search();

  queryAllemp();
  console.log(masterIds)
})

//清除
const clear = () => {
  searchClazz.value = {
    name: '',
    date: [],
    begin: '',
    end: ''
  },

    search();
}


//定义搜索班级的方法
const search = async () => {
  const result = await queryClassApi(searchClazz.value.name,
    searchClazz.value.begin,
    searchClazz.value.end,
    currentPage.value,
    pageSize.value
  );
  if (result.code) {
    clazzList.value = result.data.rows;
    total.value = result.data.total;

  }
}

//watch侦听
watch(() => searchClazz.value.date, (newVal, oldVal) => {
  if (searchClazz.value.date && searchClazz.value.date.length > 0) {
    searchClazz.value.begin = searchClazz.value.date[0];
    searchClazz.value.end = searchClazz.value.date[1];
  } else {
    searchClazz.value.begin = '';
    searchClazz.value.end = '';
  }

})

//定义空数组，用来接收查询回来的数据
const clazzList = ref([]);


/* 分页条 */
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

/* 分页条相关函数 */
const handleSizeChange = (val) => {
  search();

}
const handleCurrentChange = (val) => {
  search();
}

//对话框控制
const dialogTitle = ref('');
const dialogVisible = ref(false);

//定义对话框中的表单数据
//新增、修改的数据模型
const clazzForm = ref({
  name: '',
  room: '',
  beginDate: '',
  endDate: '',
  masterId: '',
  subject: ''
})

//添加班级
const add = () => {

  //清空上次不合法的提示
  if (clazzFormRef.value) {
    clazzFormRef.value.resetFields();
  }


  //将会话框打开
  dialogVisible.value = true;
  dialogTitle.value = '新增班级';


  //清空上次表单中填写的数据
  clazzForm.value = {
    name: '',
    room: '',
    beginDate: '',
    endDate: '',
    masterId: '',
    subject: ''
  }

}

//保存添加的班级信息
const save = async () => {

  //先进行表单校验,校验通过,再发送请求
  if (!clazzFormRef) return
  await clazzFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      //通过
      let result;
      if (clazzForm.value.id) {
        result = await updateClazzApi(clazzForm.value);
      } else {
        result = await addClazzApi(clazzForm.value);
      }



      if (result.code) {

        //成功(关闭会话框)
        dialogVisible.value = false;
        ElMessage.success('保存成功');
        search();
      } else {
        ElMessage.error(result.msg)
      }
    } else {

      //不通过
      ElMessage.error('表单校验不通过,请检查表单');
    }

  })
}

//定义数组，用于展示下拉选项
//学科数组
const subjects = ref([{ name: 'Java', value: 1 }, { name: '前端', value: 2 }, { name: '大数据', value: 3 },
{ name: 'Python', value: 4 }, { name: 'Go', value: 5 }, { name: '嵌入式', value: 6 }])


//根据下面的方法动态获取班主任信息，并展示
const masterIds = ref([]);

//定义方法，用来查询全部的部门信息
const queryAllemp = async () => {
  const result = await queryAllEmpApi();

  if (result.code) {

    //用.filter方法过滤job=1的员工
    masterIds.value = result.data.filter(item => item.job == 1);

  }
}

//表单校验规则
const clazzFormRef = ref();

//表单校验
const rules = ref({
  name: [
    { required: true, message: '班级名称为必填项', trigger: 'blur' },
    { min: 4, max: 30, message: '班级名称必须得在4-30位之间', trigger: 'blur' }
  ],
  beginDate: [
    { required: true, message: '请选择开课时间', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结课时间', trigger: 'change' }
  ],
  subject: [
    { required: true, message: '请选择学科', trigger: 'change' }
  ]
})


//根据Id查询回显
const edit = async (id) => {
  const result = await queryByIdApi(id);
  if (result.code) {

    //打开会话框
    dialogVisible.value = true;
    dialogTitle.value = '修改员工';
    clazzForm.value = result.data;
  }

}

//删除班级
const deleteClass = async (id) => {
  ElMessageBox.confirm(
    '您确定要删除该员工吗?',
    '提醒',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {

      //确认删除
      const result = await deleteClazzApi(id);
      if (result.code) {
        ElMessage.success('删除成功');
        search();
      } else {
        ElMessage.error(result.msg)
      }

    })
    .catch((err) => {

      //取消删除
      ElMessage.info('操作已取消')

    })



 
}


</script>

<template>

  <!-- 标题 -->
  <h1 style="color:lightskyblue;">班级管理</h1><br>

  <!-- 搜索框 -->
  <el-form :inline="true" :model="searchClazz" class="demo-form-inline">

    <el-form-item label="班级名称">
      <el-input v-model="searchClazz.name" style="width:250px;" placeholder="请输入班级姓名" clearable />
    </el-form-item>

    <el-form-item label="结课时间" style="margin-left: 20px;">
      <el-date-picker v-model="searchClazz.date" style="width:400px ;" type="daterange" unlink-panels
        range-separator="到" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" style="margin-left: 100px;" @click="search">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>

  <!-- 新增按钮 -->
  <el-button type="primary" style="margin-left: 10px;" @click="add">+ 新增班级</el-button><br><br>

  <!-- 表格组件 -->
  <el-table border :data="clazzList" style="width: 100%" @current-change="handleCurrentChange">
    <el-table-column label="序号" type="index" width="80" align="center" />
    <el-table-column property="name" label="班级名称" width="220" align="center" />
    <el-table-column property="room" label="班级教室" width="100" align="center" />
    <el-table-column property="masterName" label="班主任" width="100" align="center" />
    <el-table-column property="beginDate" label="开课时间" width="180" align="center" />
    <el-table-column property="endDate" label="结课时间" width="180" align="center" />
    <el-table-column property="status" label="状态" width="120" align="center" />
    <el-table-column property="updateTime" label="最后操作时间" width="220" align="center" />
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" size="small" @click="deleteClass(scope.row.id)">删除</el-button>
      </template>
    </el-table-column><br>
  </el-table>

  <!-- 分页条 -->
  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
    :page-sizes="[5, 10, 20, 30, 40, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
    @size-change="handleSizeChange" @current-change="handleCurrentChange" />


  <!-- =====会话框===== -->

  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500">

    <!-- 会话框中的表单项 -->
    <el-form :model="clazzForm" label-width="auto" :rules="rules" ref="clazzFormRef">

      <!-- 第一行 -->
      <el-form-item label="班级名称" prop="name">
        <el-input v-model="clazzForm.name" placeholder="请输入班级名称" />
      </el-form-item>

      <!-- 第二行 -->
      <el-form-item label="班级教室">
        <el-input v-model="clazzForm.room" placeholder="请填写班级教室" />
      </el-form-item>

      <!-- 第三行 -->
      <el-form-item label="开课时间" prop="beginDate">
        <el-col :span="24">
          <el-date-picker v-model="clazzForm.beginDate" type="date" placeholder="请选择开课时间" style="width: 100%" />
        </el-col>
      </el-form-item>

      <!-- 第四行 -->
      <el-form-item label="结课时间" prop="endDate">
        <el-col :span="24">
          <el-date-picker v-model="clazzForm.endDate" type="date" placeholder="请选择结课时间" style="width: 100%" />
        </el-col>
      </el-form-item>

      <!-- 第五行 -->
      <el-form-item label="班主任">
        <el-select v-model="clazzForm.masterId" placeholder="请选择" style="width: 100%">
          <el-option v-for="masterId in masterIds" :label="masterId.name" :value="masterId.id" />
        </el-select>
      </el-form-item>

      <!-- 第六行 -->
      <el-form-item label="学科" prop="subject">
        <el-select v-model="clazzForm.subject" placeholder="请选择" style="width: 100%">
          <el-option v-for="subject in subjects" :label="subject.name" :value="subject.value" />
        </el-select>
      </el-form-item>
    </el-form>


    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save"> 保存</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>

      </div>
    </template>
  </el-dialog>


</template>


<style scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 如果需要垂直居中 */
  gap: 30px;
  /* 调整按钮之间的间距 */
}
</style>